// 引入路由
import { createRouter, createWebHashHistory } from 'vue-router'
// 引入组件
import Home from '@/components/home/Home.vue'
import Login from '@/components/login/Login.vue'
import GoodsList from '@/components/home/GoodsList.vue'
import CateList from '@/components/home/CateList.vue'
import AddGoods from '@/components/home/AddGoods.vue'
import OrderList from '@/components/home/OrderList.vue'
import NeedDealOrder from '@/components/home/NeedDealOrder.vue'
import Account from '@/components/home/Account.vue'
import HomeContent from '@/components/home/HomeContent.vue'
import EditGoods from '@/components/home/EditGoods.vue'
import GoodsInfo from '@/components/home/GoodsInfo.vue'
import AddCate from '@/components/home/AddCate.vue'
import SonCateList from '@/components/home/SonCateList.vue'
import EditCate from '@/components/home/EditCate.vue'
import OrderInfo from '@/components/home/OrderInfo.vue'
import AccountInfo from '@/components/home/AccountInfo.vue'

// 创建路由表
const routes = [
  // 如果访问的是/或者''都跳转到home页面
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '',
    redirect: '/home'
  },
  // home页面路由规则
  {
    name: 'home',
    path: '/home',
    component: Home,
    redirect: '/home/index',
    children: [
      // home组件下的子组件路由规则
      { name: 'content', path: 'index', component: HomeContent },
      { path: 'goods/list', component: GoodsList },
      { path: 'cate/list', component: CateList },
      { path: 'add/goods', component: AddGoods },
      { path: 'order/list', component: OrderList },
      { path: 'deal/order', component: NeedDealOrder },
      { path: 'account', component: Account },
      { path: 'edit/goods/:id', component: EditGoods },
      { path: 'goods/info/:id', component: GoodsInfo },
      { path: 'add/cate', component: AddCate },
      { path: 'son/cate/list/:id', component: SonCateList },
      { path: 'edit/cate/:id', component: EditCate },
      {
        path: 'order/info/:id',
        component: OrderInfo
      },
      // 账单详情
      {
        path: '/home/account/info/:id',
        component: AccountInfo
      }
    ]
  },
  // 登录页面路由规则
  {
    name: 'login',
    path: '/login',
    component: Login
  }
]

// 注册路由对象
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from) => {
  // 判断用户是否登录，没有登录就跳转到登录页面
  const token = localStorage.getItem('bus_token')
  if (!token && to.name !== 'login') {
    return { name: 'login' }
  } else {
    return true
  }
})

// 导出路由对象
export default router
